/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.emergency.bean.BaseQuery;
import com.koron.emergency.bean.DrillPlanAttrBean;
import com.koron.emergency.domain.DrillPlan;
import com.koron.emergency.mapper.DrillPlanMapper;
import com.koron.emergency.service.api.DrillPlanService;
import com.koron.emergency.util.BusinessCode;
import com.koron.hazardsource.util.Immutable;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import com.koron.workflow.bean.MessageEntity;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DrillPlanServiceImpl implements DrillPlanService, AfterApprovalService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(DrillPlanServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Value("${drill_plan}")
    private String drillPlan;

    @Override
    public MessageBean<Integer> save(StaffBean user, DrillPlan plan, String approver, MultipartFile[] files) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(plan.getName())) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(plan.getCorpCode())) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_CORPCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(plan.getPurpose())) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_PURPOSE.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_PURPOSE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(plan.getManager())) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_MANAGER.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_MANAGER.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(plan.getPlace())) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_PLACE.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_PLACE.getDescription());
                return msg;
            }
            if (null == plan.getDrillMethod() || (plan.getDrillMethod() != 0 && plan.getDrillMethod() != 1 && plan.getDrillMethod() != 2)) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_METHOD.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_METHOD.getDescription());
                return msg;
            }
            if (null == plan.getDrillTime()) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_TIME.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_TIME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(plan.getSponsorDeptCode()) || StringUtils.isEmpty(plan.getSponsorDeptName())) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_SPONSORDEPTCODE.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_SPONSORDEPTCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(plan.getDrillType())) {
                msg.setCode(BusinessCode.DRILLPLANTYPE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DRILLPLANTYPE_NOT_EXIST.getDescription());
                return msg;
            }
            if (null == plan.getContingencyPlanId()) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_CONTINGENCYPLANID.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_CONTINGENCYPLANID.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(approver)) {
                msg.setCode(BusinessCode.DRILL_PLAN_EMPTY_APPROVER.getCode());
                msg.setDescription(BusinessCode.DRILL_PLAN_EMPTY_APPROVER.getDescription());
                return msg;
            }
            Integer count = factory.getMapper(DrillPlanMapper.class).doubleName(plan.getCorpCode(), plan.getName(), plan.getId());
            if (count > 0) {
                msg.setCode(BusinessCode.DRILLPLAN_DOUBLE_NAME.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_DOUBLE_NAME.getDescription());
                return msg;
            }
            plan.setStatus(0);
            plan.setIsRemove(0);
            Integer value = 0;
            Audit audit = new Audit();
            audit.setTitle((StringUtils.isEmpty(plan.getId()) ? "新增应急演练:" : "修改应急演练:") + plan.getName());
            if (StringUtils.isEmpty(plan.getId())) {
                //新增
                if(null != files){
                    List<String> atts = new ArrayList<>();
                    List<String> preAtts = new ArrayList<>();
                    for(MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        String filePath = url + "#" + file.getOriginalFilename();
                        atts.add(filePath);
                        String pdfPath = docConverterUtils.converterUpdate(file);
                        if (pdfPath != null) {
                            preAtts.add(pdfPath);
                        } else {
                            preAtts.add(filePath);
                        }
                    }
                    plan.setPreviewAttachment(new Gson().toJson(preAtts));
                    plan.setAttachment(new Gson().toJson(atts));
                }
                plan.setAddTime(plan.getUpdateTime());
                plan.setAddUser(plan.getUpdateUser());
                plan.setAddUserName(plan.getUpdateUserName());
                plan.setId(DefaultIdGenerator.getInstance().generateLongId());
                value = factory.getMapper(DrillPlanMapper.class).insert(plan);
            } else {
                //修改
                DrillPlan entity = queryOne(plan.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.DRILLPLAN_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.DRILLPLAN_NOT_EXIST.getDescription());
                    return msg;
                }
                if (entity.getStatus() == 0) {
                    msg.setCode(BusinessCode.DRILL_PLAN_IS_APPROVEING.getCode());
                    msg.setDescription(BusinessCode.DRILL_PLAN_IS_APPROVEING.getDescription());
                    return msg;
                }
//                if(null != files){
//                    List<String> atts = new ArrayList<>();
//                    if(null != entity.getAttachment()) {
//                        atts = JSONObject.parseArray(entity.getAttachment(), String.class);
//                    }
//                    for(MultipartFile file : files) {
//                        String url = clientWrapper.uploadFile(file);
//                        atts.add(url + "#" + file.getOriginalFilename());
//                    }
//                    plan.setAttachment(new Gson().toJson(atts));
//                }
                plan.setStatus(0);
                value = factory.getMapper(DrillPlanMapper.class).update(plan);
            }
            if (value > 0) {
                //提交审批计划流程
                Date date = new Date();
                audit.setAddUser(plan.getUpdateUserName());
                audit.setAddTime(date);
                audit.setUpdateUser(plan.getUpdateUserName());
                audit.setUpdateTime(date);
                audit.setFlowType(1);
                audit.setFlowName(Immutable.DRILL_PLAN);
                audit.setOperation(1);
                audit.setTarget(DrillPlanServiceImpl.class.getName());
                audit.setCorpCode(plan.getCorpCode());
                audit.setBusinessIds(plan.getId());
                audit.setInitiatorCode(plan.getUpdateUser());
                audit.setDescription(plan.getName());
                audit.setState(1);
                audit.setTemplateKey(drillPlan);
                audit.setSetCode("contingency_manage");
                audit.setInitiatorAccount(user.getUserid());
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                Map<String, Object> businessMap = new HashMap<>();
                businessMap.put("approver", approver);
                if (!flowManagement.initFlow(user, audit, businessMap)) {
                    factory.close(false);
                    msg.setCode(com.koron.accident.util.BusinessCode.FAILURE.getCode());
                    msg.setDescription("提交失败，原因是无法启动流程");
                    return msg;
                }
                factory.close();
                msg.setData(value);
                return msg;
            } else {
                factory.close(false);
                msg.setData(value);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
                return msg;
            }
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(StaffBean user, String id, String approver) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            DrillPlan entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.DRILLPLAN_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_NOT_EXIST.getDescription());
                return msg;
            }
            if (entity.getStatus() == 0) {
                msg.setCode(BusinessCode.DRILL_PLAN_IS_APPROVEING.getCode());
                msg.setDescription(BusinessCode.DRILL_PLAN_IS_APPROVEING.getDescription());
                return msg;
            }
            Integer status = entity.getStatus();
            if (status == 2) {
                entity.setIsRemove(1);
            } else {
                entity.setStatus(0);
            }
            Integer value = factory.getMapper(DrillPlanMapper.class).update(entity);
            if (value > 0) {
                if (status != 0 && status != 2) {
                    //提交删除审批计划流程
                    Date date = new Date();
                    Audit audit = new Audit();
                    audit.setAddUser(entity.getUpdateUserName());
                    audit.setAddTime(date);
                    audit.setUpdateUser(entity.getUpdateUserName());
                    audit.setUpdateTime(date);
                    audit.setFlowType(1);
                    audit.setFlowName(Immutable.DEL_DRILL_PLAN);
                    audit.setOperation(2);
                    audit.setTarget(DrillPlanServiceImpl.class.getName());
                    audit.setTitle("删除应急演练:" + entity.getName());
                    audit.setCorpCode(entity.getCorpCode());
                    audit.setBusinessIds(entity.getId());
                    audit.setInitiatorCode(entity.getUpdateUser());
                    audit.setDescription(entity.getName());
                    audit.setState(1);
                    audit.setTemplateKey(drillPlan);
                    audit.setSetCode("contingency_manage");
                    audit.setInitiatorAccount(user.getUserid());
                    audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                    Map<String, Object> businessMap = new HashMap<>();
                    businessMap.put("approver", approver);
                    if (!flowManagement.initFlow(user, audit, businessMap)) {
                        factory.close(false);
                        msg.setCode(com.koron.accident.util.BusinessCode.FAILURE.getCode());
                        msg.setDescription("提交失败，原因是无法启动流程");
                        return msg;
                    }
                }
                factory.close();
                msg.setData(value);
                return msg;
            } else {
                factory.close(false);
                msg.setData(value);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<DrillPlan> queryOne(String id) {
        MessageBean<DrillPlan> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询演练计划详情成功", DrillPlan.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            DrillPlan entity = factory.getMapper(DrillPlanMapper.class).queryOne(id);
            msg.setData(entity);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<DrillPlan>> queryByCondition(String corpCode, String name, String sponsorDeptCode, Date startTime, Date endTime, Integer start, Integer rows) {
        MessageBean<DataBean<DrillPlan>> msg = new MessageEntity<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<DrillPlan> list = factory.getMapper(DrillPlanMapper.class).queryByCondition(corpCode, name, sponsorDeptCode, startTime, getnowEndTime(endTime), start, rows);
            Integer totalNumber = factory.getMapper(DrillPlanMapper.class).countByCondition(corpCode, name, sponsorDeptCode, startTime, getnowEndTime(endTime));
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<DrillPlan> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取演练计划列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<DrillPlan>> queryAll(String corpCode, String name) {
        MessageBean<List<DrillPlan>> msg = new MessageEntity<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(corpCode)) {
                msg.setCode(BusinessCode.DRILLPLAN_EMPTY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_EMPTY_CORPCODE.getDescription());
                return msg;
            }
            List<DrillPlan> list = factory.getMapper(DrillPlanMapper.class).queryByCondition(corpCode, name, null, null, null, null, null);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取演练计划列表成功");
            msg.setData(list);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> safetyAccount(BaseQuery bean) {
        MessageBean<List<DrillPlan>> msg = new MessageEntity<>();
        if (StringUtils.isNotEmpty(bean.getEndTime())) {
            bean.setEndTime(bean.getEndTime() + "23:59:59");
        }

        try (SessionFactory factory = new SessionFactory()) {
            DrillPlanMapper mapper = factory.getMapper(DrillPlanMapper.class);
            List<DrillPlan> res = mapper.safetyAccount(bean);
            bean.setRowNumber(mapper.safetyAccountNum(bean));

            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("安全台账数据");
            msg.setData(res);
            return msg;

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<DrillPlanAttrBean>> fileList(SessionFactory factory,String id) {
        MessageBean msg = new MessageBean();
        DrillPlan entity = factory.getMapper(DrillPlanMapper.class).queryOne(id);
        if(null == entity){
            msg.setCode(BusinessCode.DRILLPLAN_NOT_EXIST.getCode());
            msg.setDescription(BusinessCode.DRILLPLAN_NOT_EXIST.getDescription());
            return msg;
        }
        if(null == entity.getAttachment() || entity.getAttachment().isEmpty()){
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setData(new ArrayList<>());
            return msg;
        }
        List<DrillPlanAttrBean> result = new ArrayList<>();
        if(entity.getAttachment() != null && entity.getPreviewAttachment() != null) {
            List<String> attachments = JSONObject.parseArray(entity.getAttachment(), String.class);
            List<String> preAttachments = JSONObject.parseArray(entity.getPreviewAttachment(), String.class);
            for (int i = 0; i<attachments.size(); i++ ) {
                String[] split = attachments.get(i).split("#");
                String[] split1 = preAttachments.get(i).split("#");
                DrillPlanAttrBean bean = new DrillPlanAttrBean();
                bean.setPreFileAddress(split1[0]);
                bean.setFileAddress(split[0]);
                bean.setFileName(split[1]);
                result.add(bean);
            }
        }
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription("获取附件成功");
        msg.setData(result);
        return msg;
    }

    private Date getnowEndTime(Date date) {
        if (null != date) {
            Calendar todayEnd = Calendar.getInstance();
            todayEnd.setTime(date);
            todayEnd.set(Calendar.HOUR_OF_DAY, 23);
            todayEnd.set(Calendar.MINUTE, 59);
            todayEnd.set(Calendar.SECOND, 59);
            todayEnd.set(Calendar.MILLISECOND, 999);
            return todayEnd.getTime();
        } else {
            return null;
        }
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            DrillPlan plan = factory.getMapper(DrillPlanMapper.class).queryOne(audit.getBusinessIds());
            if (plan != null) {
                plan.setStatus(1);
                factory.getMapper(DrillPlanMapper.class).update(plan);
                //向将要参与演练的参与人员和负责人发送消息
                List<Message> messageList = new ArrayList<>();
                List<String> codes = new ArrayList<>();
                codes.add(plan.getManager());
                if (StringUtils.isNotEmpty(plan.getParticipant())) {
                    List<String> code1 = JSONObject.parseArray(plan.getParticipant(), String.class);
                    codes.addAll(code1);
                }
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String xx = formatter.format(plan.getDrillTime());
                StringBuilder text = new StringBuilder();
                text.append("演练时间：").append(formatter.format(plan.getDrillTime())).append("，主办单位为：").append(plan.getSponsorDeptName());
                if (StringUtils.isNotEmpty(plan.getCooperationDeptName())) {
                    text.append("，协办单位：").append(JSONObject.parseArray(plan.getCooperationDeptName(), String.class).stream().collect(Collectors.joining(",")));
                }
                text.append("。负责人为：").append(plan.getManagerName());
                if (StringUtils.isNotEmpty(plan.getParticipantName())) {
                    text.append(",参与人员为：").append(JSONObject.parseArray(plan.getParticipantName(), String.class).stream().collect(Collectors.joining(",")));
                }
                text.append("。演练地点为：").append(plan.getPlace()).append("。演练目的为：").append(plan.getPurpose()).append("。演练方式为:").
                        append(plan.getDrillMethod() == 0 ? "桌面演练" : (plan.getDrillMethod() == 1 ? "功能演练" : "全面演练"));
                for (String code : codes) {
                    Message message = new Message();
                    message.setId(DefaultIdGenerator.getInstance().generateLongId());
                    message.setAddTime(plan.getUpdateTime());
                    message.setIsRemove(0);
                    message.setIsRead(0);
                    message.setAddUser(plan.getUpdateUserName());
                    message.setUpdateUser(plan.getUpdateUserName());
                    message.setUpdateTime(plan.getUpdateTime());
                    message.setTitle("您有一项新的演练计划待查收");
                    message.setContent(text.toString());
                    message.setReceiverCode(code);
                    messageList.add(message);
                }
                if (null != messageList && messageList.size() > 0)
                    factory.getMapper(MessageMapper.class).batchInsert(messageList);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            DrillPlan plan = factory.getMapper(DrillPlanMapper.class).queryOne(audit.getBusinessIds());
            if (plan != null) {
                plan.setStatus(1);
                plan.setIsRemove(1);
                factory.getMapper(DrillPlanMapper.class).update(plan);
                //向将要参与演练的参与人员和负责人发送消息
                List<Message> messageList = new ArrayList<>();
                List<String> codes = new ArrayList<>();
                codes.add(plan.getManager());
                if (StringUtils.isNotEmpty(plan.getParticipant())) {
                    List<String> code1 = JSONObject.parseArray(plan.getParticipant(), String.class);
                    codes.addAll(code1);
                }
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String xx = formatter.format(plan.getDrillTime());
                StringBuilder text = new StringBuilder();
                text.append("主办单位为：").append(plan.getSponsorDeptName()).append("演练时间为：").append(formatter.format(plan.getDrillTime()));
                if (StringUtils.isNotEmpty(plan.getCooperationDeptName())) {
                    text.append("，协办单位：").append(JSONObject.parseArray(plan.getCooperationDeptName(), String.class).stream().collect(Collectors.joining(",")));
                }
                text.append("。负责人为：").append(plan.getManagerName());
                if (StringUtils.isNotEmpty(plan.getParticipantName())) {
                    text.append(",参与人员为：").append(JSONObject.parseArray(plan.getParticipantName(), String.class).stream().collect(Collectors.joining(",")));
                }
                text.append("。演练地点为：").append(plan.getPlace()).append("。演练目的为：").append(plan.getPurpose()).append("。演练方式为:").
                        append(plan.getDrillMethod() == 0 ? "桌面演练" : (plan.getDrillMethod() == 1 ? "功能演练" : "全面演练"));
                text.append("。这项应急演练已被取消");
                for (String code : codes) {
                    Message message = new Message();
                    message.setId(DefaultIdGenerator.getInstance().generateLongId());
                    message.setAddTime(plan.getUpdateTime());
                    message.setIsRemove(0);
                    message.setIsRead(0);
                    message.setAddUser(plan.getUpdateUserName());
                    message.setUpdateUser(plan.getUpdateUserName());
                    message.setUpdateTime(plan.getUpdateTime());
                    message.setTitle("演练计划取消");
                    message.setContent(text.toString());
                    message.setReceiverCode(code);
                    messageList.add(message);
                }
                if (null != messageList && messageList.size() > 0)
                    factory.getMapper(MessageMapper.class).batchInsert(messageList);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            DrillPlan plan = factory.getMapper(DrillPlanMapper.class).queryOne(audit.getBusinessIds());
            if (plan != null) {
                if (Immutable.DRILL_PLAN.equals(audit.getFlowName())) {
                    //保存应急计划流程被废弃
                    if (plan.getAddTime().compareTo(plan.getUpdateTime()) == 0) {
                        //新增被废弃
                        plan.setStatus(2);
                    } else {
                        //修改流程被废弃
                        plan.setStatus(3);
                    }
                }
                if (Immutable.DEL_DRILL_PLAN.equals(audit.getFlowName())) {
                    //删除应急计划流程被废弃
                    plan.setStatus(4);//删除被驳回
                }
                factory.getMapper(DrillPlanMapper.class).update(plan);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(DrillPlanServiceImpl.class.getName(), this);
    }


    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
